package com.demo2.todo.controller;

import com.demo2.todo.exception.ResourceNotFoundException;
import com.demo2.todo.model.dto.TagRequest;
import com.demo2.todo.model.dto.TagResponse;
import com.demo2.todo.model.entity.Tag;
import com.demo2.todo.model.entity.User;
import com.demo2.todo.repository.TagRepository;
import com.demo2.todo.service.UserService;
import com.demo2.todo.utils.SecurityUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author evi
 */
@RestController
@RequestMapping("/tags")
@RequiredArgsConstructor
public class TagController {
    private final TagRepository tagRepository;
    private final UserService userService;

    @GetMapping("/user")  // 移除路径中的{userId}，通过token识别用户
    public ResponseEntity<List<TagResponse>> getUserTags() {
        try {
            // 获取当前登录用户（确保已登录，未登录会被Security拦截）
            User currentUser = SecurityUtils.getCurrentUser();

            // 查询该用户的标签
            List<Tag> userTags = tagRepository.findByUserId(currentUser.getId());

            // 转换为TagResponse（避免直接返回实体类）
            List<TagResponse> responses = userTags.stream()
                    .map(tag -> {
                        TagResponse response = new TagResponse();
                        response.setId(tag.getId());
                        response.setName(tag.getName());
                        response.setUserId(currentUser.getId()); // 设置用户ID
                        return response;
                    })
                    .collect(Collectors.toList());

            return ResponseEntity.ok(responses);
        } catch (Exception e) {
            // 打印错误日志（关键：查看具体报错原因）
            e.printStackTrace();
            // 返回友好错误信息
            return ResponseEntity.internalServerError().body(null);
        }
    }

    @PostMapping
    public ResponseEntity<Tag> createTag(@RequestBody TagRequest request) {
        User user = userService.getCurrentUserEntity();
        Tag tag = new Tag();
        tag.setName(request.getName());
        tag.setUser(user);
        return ResponseEntity.ok(tagRepository.save(tag));
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteTag(@PathVariable Long id) {
        User user = userService.getCurrentUserEntity();
        Tag tag = tagRepository.findByIdAndUserId(id, user.getId())
                .orElseThrow(() -> new ResourceNotFoundException("标签不存在"));
        tagRepository.delete(tag);
        return ResponseEntity.noContent().build();
    }

    @PutMapping("/{id}")
    public ResponseEntity<Tag> updateTag(@PathVariable Long id, @RequestBody TagRequest request) {
        User user = userService.getCurrentUserEntity();
        Tag tag = tagRepository.findByIdAndUserId(id, user.getId())
                .orElseThrow(() -> new ResourceNotFoundException("标签不存在"));
        tag.setName(request.getName());
        return ResponseEntity.ok(tagRepository.save(tag));
    }
}